﻿using System;
using UnityEngine;

namespace Core
{
    public interface IJoystick
    {
        float GetPercent();

        event Action<Vector2> OnMoveStart;
        event Action<Vector2> OnMove;
        event Action OnMoveEnd;
    }

    /// <summary>
    /// 前缀 joystick_XXX Button
    /// </summary>
    public class UIJoystick : UIWidget
    {
        public IJoystick Joystick;

        private float percent;
        public Vector2 Delta { get; private set; }

        public event Action<Vector2> OnMoveStart;
        public event Action<Vector2> OnMove;
        public event Action OnMoveEnd;

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            Joystick = go.GetComponent<IJoystick>();

            Joystick.OnMoveStart += OnMoveStartHandler;
            Joystick.OnMove += OnMoveHandler;
            Joystick.OnMoveEnd += OnMoveEndHandler;

            percent = Joystick.GetPercent();
            percent *= percent;
        }


        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            Joystick.OnMoveStart -= OnMoveStartHandler;
            Joystick.OnMove -= OnMoveHandler;
            Joystick.OnMoveEnd -= OnMoveEndHandler;
            Joystick = null;
        }

        private void OnMoveStartHandler(Vector2 pos)
        {
            OnMoveStart?.Invoke(pos);
        }

        private void OnMoveHandler(Vector2 obj)
        {
            Delta = obj.normalized;
            if (Delta.sqrMagnitude < percent)
            {
                return;
            }

            OnMove?.Invoke(Delta);
        }

        private void OnMoveEndHandler()
        {
            OnMoveEnd?.Invoke();
        }
    }
}